package com.example.canavar;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Locale;
import java.util.Set;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.preference.PreferenceManager;
import android.support.v4.app.NotificationCompat;
import android.support.v4.app.TaskStackBuilder;
import android.util.Log;

import com.example.utils.SearchResult;
import com.example.utils.SearchResultManager;
import com.example.utils.SearchTaskDelegate;
import com.example.utils.Utils;

public class SearchTask extends AsyncTask<String, String, String> {

	private static final int MY_NOTIFICATION_ID = 1;
	public static final String START= "task_start";
	public static final String END = "task_end";
	public static boolean isRunning = false;
	private SearchTaskDelegate mDelegate = null;

	Document doc;
	NotificationManager notificationManager;
	Notification myNotification;
	
	private Context mContext;

	public SearchTask(Context context) {
		mContext = context;		
	}

	protected String doInBackground(String... params) {
		Utils.Log("******** AsyncTask started, NOT running on UI thread.");

		// LaunchParser
		SharedPreferences shared = PreferenceManager
				.getDefaultSharedPreferences(mContext);
		// Shop Entries
		Set<String> shops = shared.getStringSet(
				SettingsFragment.SHOPS_PREF_KEY, null);

		// Brand Entries
		Set<String> brands = shared.getStringSet(
				SettingsFragment.BRANDS_PREF_KEY, null);

		for (SearchResult res : search(shops, brands)) {
			addNotification(res.getBrand(), res.getShop(), mContext);	
			SearchResultManager.getInstance().addResult(res);
			SearchResultManager.getInstance().addLog(res.getShop()+ " - " + res.getBrand());
		}

		return "";
	}

	@Override
	protected void onPreExecute() {
		// TODO Auto-generated method stub
		super.onPreExecute();
		isRunning = true;
		SearchResultManager.getInstance().addLog(SearchTask.START);
		
		// if the user has launched the search manually
		if (mDelegate != null) {
			mDelegate.onTaskStarted("");
		}				 
	}

	protected void onProgressUpdate(String... progress) {

//		SearchResultManager.getInstance().addLog(progress[0]);
		
		// if the user has launched the search manually
		if (mDelegate != null) {
			mDelegate.onTaskUpdate(progress[0]);
		}
	}

	@Override
	protected void onPostExecute(String result) {
		// TODO Auto-generated method stub
		super.onPostExecute(result);		
		Utils.Log("******** AsyncTask finished ********");

		SearchResultManager.getInstance().addLog(SearchTask.END);
		isRunning = false;

		if (mDelegate != null) {
			mDelegate.onTaskCompleted(result);
		}

	}

	private void publishUpdate(String updateText) {
		Utils.Log(updateText);
		publishProgress(updateText);
	}

	private void addNotification(String brand, String shop, Context context) {
		// Notification
		// notificationManager = (NotificationManager)
		// getSystemService(Context.NOTIFICATION_SERVICE);
		String message = brand + " found in " + shop;
		String title = mContext.getResources().getString(R.string.app_name);
		Utils.Log("Timer task trying to show notification. Message: " + message);
		// notificationManager.notify(MY_NOTIFICATION_ID, myNotification);

		NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(
				context).setSmallIcon(R.drawable.ic_launcher)
				.setContentTitle(title).setContentText(message);
		// Creates an explicit intent for an Activity in your app
		Intent resultIntent = new Intent(context, MainActivity.class);

		// The stack builder object will contain an artificial back stack for
		// the
		// started Activity.
		// This ensures that navigating backward from the Activity leads out of
		// your application to the Home screen.
		TaskStackBuilder stackBuilder = TaskStackBuilder.create(context);
		// Adds the back stack for the Intent (but not the Intent itself)
		stackBuilder.addParentStack(MainActivity.class);
		// Adds the Intent that starts the Activity to the top of the stack
		stackBuilder.addNextIntent(resultIntent);
		PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(0,
				PendingIntent.FLAG_UPDATE_CURRENT);
		mBuilder.setContentIntent(resultPendingIntent);
		NotificationManager mNotificationManager = (NotificationManager) mContext
				.getSystemService(Context.NOTIFICATION_SERVICE);
		// mId allows you to update the notification later on.
		mNotificationManager.notify(MY_NOTIFICATION_ID, mBuilder.build());
	}

	private ArrayList<SearchResult> search(Set<String> shops, Set<String> brands) {
		Utils.Log(" Let the hunt begin.. ");
		ArrayList<SearchResult> results = new ArrayList<SearchResult>();
		try {
			for (String shopUrl : shops) {
				String shop = Utils.PrefUtils.getEntryFromValue(mContext,
						R.array.shop_values, R.array.shop_entries, shopUrl);

				doc = Jsoup.connect(shopUrl).get();
				publishUpdate(" Siradaki dukkan " + shop);

				for (String brand : brands) {
					// Utils.Log("Connecting to shopUrl = " + shopUrl);
					publishUpdate(brand + " araniyor ");

					if (doc.body().text().toLowerCase(Locale.ENGLISH)
							.contains(brand.toLowerCase())) {

						publishUpdate("Indirim var! " + shop + " -> " + brand);

						results.add(new SearchResult(brand, shop, Utils
								.getDayFromTime(Utils.getNow()), shopUrl));
					} else {
//						publishUpdate(shop + " icin " + brand
//								+ " bulunamadi.");
					}
				}
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return results;

	}

	public void setDelegate(SearchTaskDelegate mDelegate) {
		this.mDelegate = mDelegate;
	}
}
